<template>
  <Modal v-model="showModal"  title="国标语音对讲"  width="350px" :mask-closable="false" :closable="false"
         :mask=true
         :footer-hide=true
         @on-visible-change="onVisibleChange">
    <audio id="talkPlayer" ref="talkPlayer" autoplay v-show="1==0" muted> </audio>
    <div class="volCont" v-show="spining" style="background-color: #0c0c0c;display: flex;justify-content: center;align-items: center">
      <Spin size="large" ></Spin>
<!--      <div v-for="item in animaItems" class="item" :id="item.id" :ref="item.id" :style="item.style"></div>-->
    </div>
    <div v-show="!spining" style="width: 100%;height: 100%;background-color: #00060c" >
      <canvas id="audioCanvas" ref="audioCanvas" style="width: 100%;height: 100%" ></canvas>
    </div>
    <div style="height: 32px;display: flex;justify-content: center">
      <Button @click="close">关闭</Button>
    </div>
  </Modal>
</template>
<script>
import Device from "@/api/Device";
import MediaDevice from "@/api/MediaDevice";
import config from '@/config'
import {apiResult} from "@/libs/util";
export default {
  name:"GbTalkPlayer",
  data(){
    return{
      api: new Device(),
      push:{
        url: null,
        deviceId: null,
        stream: null,
        app: "live",
        host: null
      },
      spining: true, //加载条
      talkElement: null,
      style1:{
        transition: "height 0.15s ease",
        height:'80px'},
      showModal:false,
      //elementPlayer: null,
      animationTimer:null,
      mediaStream:null,
      audioCtx:null,
      waveTimer:null,
      callBack:null
    }
  },
  methods:{
    clearAllTimer(){
      if (this.animationTimer != null){
        this.clearTimer(this.animationTimer)
      }
    },
    /**
     * 关闭某定时器
     */
    clearTimer(timer){
      if (!!timer){
        clearInterval(timer);
        timer = null;
      }
    },
    close(){
      this.stop();
      this.clearAllTimer();
      this.api.stopGbTalk(this.push.deviceId,this.push.app,this.push.stream).then((res)=>{
          apiResult(res.data,true,result=>{

          })
      })

      this.MediaStreamTrack && this.MediaStreamTrack.stop();
      if (!!this.audioCtx){
        this.audioCtx.close();
      }

      if (!!this.waveTimer){
        clearInterval(this.waveTimer)
        this.waveTimer=null;
      }
      this.showModal = false;
    },
    openDialog(deviceId,channelId,callBack) {
      this.showModal = true;
      this.callBack = callBack;
      const _this = this;
      const constraints = { audio: true};
      navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
        //关闭 MIC使用
        _this.MediaStreamTrack=typeof mediaStream.stop==='function'?mediaStream:mediaStream.getTracks()[0];
        _this.mediaStream = mediaStream;
        _this.init(deviceId,channelId,callBack);
      }).catch((err)=>{
        console.log("！！！！ GbTalkPlayer::openDialog, %o",err)
        _this.returnCallBack({code:-1,msg:"设备初始化失败"});
      })
    },
    returnCallBack(message){
      if (!!this.callBack){
        this.callBack(message);
        if (message.code !== 0){
          this.showModal = false;
        }
      }
    },

    init(deviceId,channelId){
      this.push.deviceId = deviceId;
      this.push.stream = deviceId + "_" + channelId + "_gbtalk";
      let pushUrl = "http://192.168.0.129:8080/index/api/webrtc?app=live&stream=" + this.push.stream + "&type=push";
      this.push.url = this.api.getPushUrl(pushUrl);
      //console.log(">>>>> push=%o",this.push);
      this.api.playGbTalk(deviceId,this.push.app,this.push.stream).then((res)=>{
          apiResult(res.data,false,result=>{
            //广播发出成功，可以推流了
            this.startPushStream();
          },err=>{
            // 广播失败，关闭窗口
            this.stop();
            this.returnCallBack({code:-1,msg:res.data.msg});
          });
      })

      //开始推流
/*      const url = new URL(this.pushUrl);
      console.log(url); // 输出完整的URL对象信息
      // 获取URL的属性值
      console.log(url.protocol); // 输出 "https:"
      console.log(url.hostname); // 输出 "www.example.com"
      console.log(url.port); // 输出 ""（没有指定端口）
      console.log(url.pathname); // 输出 "/path"
      console.log(url.search); // 输出 "?param1=value1&param2=value2"
      console.log(url.hash); // 输出 ""（没有锚点）*/

      /* console.log(this.videoUrl);
                      const url = new URL(this.videoUrl);
                      console.log(url); // 输出完整的URL对象信息
                      // 获取URL的属性值
                      console.log(url.protocol); // 输出 "https:"
                      console.log(url.hostname); // 输出 "www.example.com"
                      console.log(url.port); // 输出 ""（没有指定端口）
                      console.log(url.pathname); // 输出 "/path"
                      console.log(url.search); // 输出 "?param1=value1&param2=value2"
                      console.log(url.hash); // 输出 ""（没有锚点）
                      // 修改URL的部分属性值
                      url.host = 'newexample.com';
                      url.pathname += '/subpage';
                      url.searchParams.set('param3', 'value3');
                      console.log(url); // 输出更新后的URL对象信息*/
    },

    onVisibleChange(state){
      this.spining = state;
      if (!state){
/*        this.showModal = false;
        if (!!this.animationTimer){
          clearInterval(this.animationTimer);
          this.animationTimer=null;
        }*/
        this.$emit("close-talk")
      }else{
        //this.showModal = true;
        //
        // his.animation();
      }
    },
    /**
     * 开始推流
     */
    startPushStream(){
      const _this = this;
      this.talkPlayer = new ZLMRTCClient.Endpoint({
        element: _this.talkElement,// video 标签
        debug: false,// 是否打印日志
        zlmsdpUrl: _this.push.url,//流地址
        simulecast: false,
        useCamera: false,
        audioEnable: true,
        videoEnable: false,
        recvOnly: false,
      })
      //协商出错
      this.talkPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
        console.error('ICE 协商出错: %o',e)
        _this.returnCallBack({code:-1,msg:"推语音流出错"})
      });
      this.talkPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state) {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
        console.log('当前状态==>', state)
        if ("connected" === state){
          _this.spining = false;
          _this.returnCallBack({code:0,msg:"开始对讲"})
          _this.genAudioWave();
        }
      });
    },

    /**
     * 音频波形图
     */
    genAudioWave(){
      const _this = this;
      if (!!this.mediaStream){
        new MediaDevice().audioWave(_this.mediaStream,_this.$refs.audioCanvas,
          (res)=>{
            //console.log(">>>> audioWave: res=%o",res);
            _this.audioCtx = res.audioCtx;
            _this.waveTimer = res.timer;
          })
      }
    },

    stop(){
      if(this.talkPlayer){
        this.talkPlayer.close();
        this.talkPlayer = null;
        if(!!this.talkElement){
          this.talkElement.srcObject = null;
          this.talkElement.load();
          //this.talkElement = null;
        }
      }

      this.MediaStreamTrack && this.MediaStreamTrack.stop();
      this.mediaStream = null;
      if (!!this.audioCtx){
        this.audioCtx.close();
        this.audioCtx=null;
      }

      if (!!this.waveTimer){
        clearInterval(this.waveTimer)
        this.waveTimer=null;
      }
    },
  },
  mounted() {
    const _this = this;
    this.$nextTick(()=>{
      _this.talkElement = document.getElementById("talkPlayer")
      //console.log("_this.talkElement: %o",_this.talkElement)
    })
  },
  beforeDestroy() {
    this.stop();
    this.clearAllTimer();
  }
}
</script>
<style lang="less">
//音频动画
.volCont {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 300px;
}

.item {
  background-color: blue;
  width: 10px;
  height: 50px;
  margin-right: 8px;
}
</style>
